﻿using Google.Protobuf;
using OpenCvSharp;

namespace ScienceRpcServe.Utils;

public static class ConvertUtils
{
    public static ByteString ConvertToByteString(this Mat? mat)
    {
        if (mat == null) return ByteString.Empty;
        mat.ConvertTo(mat, OpenCvSharp.MatType.CV_8UC1);
        return ByteString.CopyFrom(mat.ToBytes());
    }

    public static ByteString ConverToOriginalByteString(this Mat? mat)
    {
        if (mat == null) return ByteString.Empty;
        return ByteString.CopyFrom(mat.ToBytes());
    }

    public static Mat? ConvertToMat(this ByteString bytes)
    {
        if (bytes.IsEmpty) return null;
        var imageData = bytes.ToByteArray();
        using var ms = new MemoryStream(imageData);
        return Mat.FromStream(ms, ImreadModes.Color);
    }

}
